import { Form, Input, Button, Tooltip, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { QuestionOutlined } from '@ant-design/icons';
import { queryRule, updateRule } from './service';
import styles from './style.less';

interface ConfigData {
  list: any;
}

const initState: ConfigData = {
  list: [],
};

const ConfigSite = () => {
  const [form] = Form.useForm();
  const [state, setState] = useState(initState);

  const loadData = async () => {
    const res = await queryRule({ configName: 'site' });
    if (res.code === 0) {
      const { data } = res;

      setState({
        list: data.list,
      });
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const onFinish = async (values: any) => {
    console.log(values);
    const { code } = await updateRule(values);
    if (code === 0) {
      message.success('更新成功');
    }
  };

  const { list } = state;
  const initialValues: any = {};
  list.forEach((it: any) => {
    initialValues[it.field] = it.defaultValue;
  });
  console.log(initialValues, 'initialValues')
  form.setFieldsValue(initialValues);

  return (
    <PageHeaderWrapper>
      <div className="cardBody">
        <Form
          form={form}
          onFinish={onFinish}
          style={{ width: '70%' }}
          className={styles.container}
        // initialValues={initialValues}
        >
          {list.map((it: any) => (
            <div>
              <Form.Item
                className={it.isOccupyOneline ? styles.occupyTwoCol : null}
                name={it.field}
                label={
                  <span>
                    {it.name}
                    &nbsp;
                    {it.helpText && (
                      <Tooltip title={it.helpText}>
                        <QuestionOutlined />
                      </Tooltip>
                    )}
                  </span>
                }
                rules={[{ required: it.isRequired }]}
              >
                {it.type === 'TEXT' ? <Input /> : <Input.TextArea />}
              </Form.Item>
            </div>
          ))}
          <Form.Item wrapperCol={{ offset: 3 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </PageHeaderWrapper>
  );
};

export default ConfigSite;
